import { captcha } from '../service/index'

export default {
  'times': 60,
  'timeLeft': 0,
  'timer': '',
  'phoneNumber': 0,
  'opts': {},
  send: function (phoneNumber, opts) {
    let _this = this

    return new Promise(function (resolve, reject) {
      _this.phoneNumber = phoneNumber
      if (!_this.isPhone()) {
        reject(new Error())
      }

      _this.opts = opts
      _this.init()
      captcha(phoneNumber).then(function (response) {
        resolve(response, _this)
      }).catch((error) => {
        reject(error)
      })
    })
  },

  init: function () {
    if (this.opts.times && parseInt(this.opts.times) > 0) {
      this.times = parseInt(this.opts.times)
    }
  },

  clearInterval: function () {
    clearInterval(this.timer)
  },

  isPhone: function () {
    return (/^1[34578]\d{9}$/.test(this.phoneNumber))
  },

  countDown: function () {
    let _this = this
    this.timeLeft = this.times
    this.timer = setInterval(function () {
      _this.timeLeft--
      if (_this.timeLeft === 0) {
        _this.clearInterval()
      }
    }, 1000)
  }
}
